﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using AtletIS.Shared.Helpers;
using AtletIS.Shared.Data.aDbDataSetTableAdapters;
using System.IO;

namespace AtletIS.Shared.Forms
{
    public partial class frmTotalResults : Form
    {
        private DisciplinesTableAdapter taDisciplines = new DisciplinesTableAdapter();
        
        public frmTotalResults()
        {
            InitializeComponent();
            this.Icon = Properties.Resources.AtletIS64;
        }

        private void frmTotalResults_Load(object sender, EventArgs e)
        {
            this.lblTitle.Text = Globals.ActiveCompetition.Name;

            DataTable dtDisciplines = DatabaseHelper.GetDisciplinesByCompetitionId(Globals.ActiveCompetition.ID); // taDisciplines.GetByCompetitionId(Globals.ActiveCompetition.ID);
            foreach (DataRow dr in dtDisciplines.Rows)
            {
                tvDisciplines.Nodes.Add(dr["ID"].ToString(), dr["Name"].ToString());
            }
        }

        private void tsbGenerate_Click(object sender, EventArgs e)
        {
            string path = Path.Combine("Ext", "total_results.html");
            StreamWriter sw = new StreamWriter(path, false, Encoding.Default);

            try
            {
                ResultsHelper.ResultsHeader(sw);

                foreach (TreeNode tn in tvDisciplines.Nodes)
                {
                    if (tn.Checked)
                    {
                        sw.WriteLine("<h3>" + tn.Text + " - Absolútne poradie" + "</h3>");
                        TotalResultsHelper.ForDisciplineIdTable(Convert.ToInt32(tn.Name), Globals.ActiveCompetition.ID, sw);
                    }
                }
                
                ResultsHelper.ResultsFooter(sw);
            }
            catch (Exception ex)
            {
                MessageBox.Show("ERROR: " + ex.Message + Environment.NewLine + "STACK: " + ex.StackTrace, "Absolútne poradie", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                sw.Close();
                sw.Dispose();
                System.Diagnostics.Process.Start(path);
            }
        }

        private void tsbClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void chkAll_CheckedChanged(object sender, EventArgs e)
        {
            foreach (TreeNode tn in tvDisciplines.Nodes)
            {
                tn.Checked = chkAll.Checked;
            }
        }
    }
}
